package com.sky.controller;

import com.sky.constant.MessageConstant;
import com.sky.properties.MinioProperties;
import com.sky.entity.result.Result;
import com.sky.utils.FaceRecognitionUtil;
import io.minio.MinioClient;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
* 人脸识别管理
* @author  wjb
* @data 2025-2-24
* */
@Slf4j
@RestController
@RequestMapping("/admin/face-recognition")
@Tag(name = "人脸识别管理", description = "人脸识别管理")
@CrossOrigin
public class FaceRecognitionController {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;

    // 线程池处理多个流
    private final ExecutorService executor = Executors.newCachedThreadPool();

    // 存储活动的抓取器
    private final Map<String, FaceRecognitionUtil.StreamWorker> activeWorkers = new HashMap<>();


    @PostMapping("/start")
    @Operation(summary = "开始人脸识别")
    public Result startStream(@RequestParam String rtspUrl) {
        try {

            // 生成唯一任务ID
            String taskId = "task_" + System.currentTimeMillis();
            System.out.println("Start stream: " + taskId);

            // 创建并启动抓取线程
            FaceRecognitionUtil.StreamWorker worker = new FaceRecognitionUtil.StreamWorker(taskId, rtspUrl, minioClient, minioProperties.getBucketName());
            executor.submit(worker);
            activeWorkers.put(taskId, worker);
            return Result.success(MessageConstant.SUCCESS_START_STREAM);
        } catch (Exception e) {
            return Result.error("Error starting stream: " + e.getMessage());
        }
    }

    @PostMapping("/stop")
    @Operation(summary = "停止人脸识别")
    // 处理停止流请求
    public Result stopStream(@RequestParam String taskId) {
        // 根据任务ID获取对应的流工作线程
        FaceRecognitionUtil.StreamWorker worker = activeWorkers.get(taskId);
        // 如果流工作线程存在
        if (worker != null) {
            // 停止流工作线程
            worker.stop();
            // 从活动工作线程集合中移除该流工作线程
            activeWorkers.remove(taskId);
            // 返回成功响应
            return Result.success(MessageConstant.SUCCESS_STOP_STREAM);
        }
        // 返回错误响应
        return Result.error(MessageConstant.INVALID_REQUEST);
    }



}
